'use client'

import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { _signUpWithGoogle } from '@/utils/firebase.js'
import useRequest from '@/utils/request'
import { useSelector, useDispatch } from 'react-redux'
import { selectUser, setUser } from '@/store/user-slice'
import clsx from 'clsx'

export default function SignUpBtn({ className, children }) {
  const router = useRouter()
  const request = useRequest()
  const dispatch = useDispatch()
  const user = useSelector(selectUser)

  async function Login() {
    try {
      const data = await _signUpWithGoogle()
      const res = await request.post('account/signin_or_signup_with_source', data)

      dispatch(setUser(res.data))

      goDashboard()
    } catch (error) {
      console.log(error)
    }
  }

  async function goDashboard() {
    router.push('/projects')
  }

  if (user?.token) {
    return (
      <Button
        className="bg-white text-[#ff4d4d] hover:bg-gray-100 px-8 py-3 text-lg font-medium"
        onClick={() => {
          goDashboard()
        }}
      >
        Dashboard
      </Button>
    )
  }

  return (
    <Button
      className={clsx('bg-white text-[#ff4d4d] hover:bg-gray-100 px-8 py-3 text-lg font-medium', className)}
      onClick={() => {
        Login()
      }}
    >
      {children || 'Sign Up for Free'}
    </Button>
  )
}
